package cn.nullpointer95.fileprocess.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * 文件 IO 接口类
 *
 * @author NullPointer95
 * @version 1.0
 */
@RestController
@Api(tags={"文件 IO 接口"})
public class FileIOController {

    /**
     * 文件上传接口
     */
    @PostMapping("uploadFile")
    @ApiOperation(value = "上传文件", notes = "上传文件并返回上传结果", httpMethod = "POST")
    public String uploadFile(
            @ApiParam(value = "上传的文件",required = true) @RequestParam(value = "file") MultipartFile file,
            HttpServletRequest request) throws URISyntaxException, IOException {

        String pathName = ResourceUtils.getURL("classpath:").getPath();
        int suffixIndex = pathName.indexOf("/target");
        pathName = pathName.substring(0,suffixIndex);
        File tempFile = new File(pathName+"/temp_file/temp.md");
        try(BufferedInputStream inputBuffer = new BufferedInputStream(file.getInputStream());
                FileOutputStream output = new FileOutputStream(tempFile)){

            byte[] buffer = new byte[1024];
            while(inputBuffer.read(buffer) != -1){
                output.write(buffer);
            }
        }
        return "Upload success";
    }
}
